<script setup lang="ts">
import { computed, unref, ref, watch, nextTick } from "vue";
// import Iconify from "@purge-icons/generated";
import Iconify from "@iconify/iconify/dist/iconify";
import { isString } from "@/utils/is";

const props = defineProps({
  // icon name
  icon: {
    type: String,
    default: "",
  },
  color: String,
  size: {
    type: [String, Number],
    default: 16,
  },
  extendStyle: {
    type: Object,
    default: () => ({}),
  },
});

const elRef = ref<ElRef>(null);

const symbolId = computed(() => {
  return props.icon;
});

const getIconifyStyle = computed(() => {
  const { color, size, extendStyle } = props;
  return {
    fontSize: isString(size) ? size : `${size}px`,
    color,
    ...extendStyle,
  };
});

const updateIcon = async (icon: string) => {
  const el = unref(elRef);
  if (!el) return;

  await nextTick();

  if (!icon) return;

  const svg = Iconify.renderSVG(icon, {});
  if (svg) {
    el.textContent = "";
    el.appendChild(svg);
  } else {
    const span = document.createElement("span");
    span.className = "iconify";
    span.dataset.icon = icon;
    el.textContent = "";
    el.appendChild(span);
  }
};

watch(
  () => props.icon,
  (icon: string) => {
    updateIcon(icon);
  }
);
</script>

<template>
  <span ref="elRef" :class="$attrs.class" :style="getIconifyStyle">
    <span class="iconify" :data-icon="symbolId"></span>
  </span>
</template>
